package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.UsualTaskVO;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Usual;
import com.tongzhan.entity.religion.UsualTask;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.UsualRepository;
import com.tongzhan.repository.religion.UsualTaskRepository;
import com.tongzhan.service.UsualTaskService;
import com.tongzhan.utils.DateSwitcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UsualTaskServiceImpl implements UsualTaskService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UsualRepository usualRepository;

    @Autowired
    private UsualTaskRepository usualTaskRepository;

    @Override
    public Return newUsualTask(UsualTask task) {
        task.setCreateTime(LocalDateTime.now());
        try {
            usualTaskRepository.insert(task);
        } catch (Exception e) {
            return new Return(Return.EXEXCEPTION, "新增报送任务失败");
        }
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return getUsualTaskList(String userId, Integer page, Integer size) {
        //查询用户信息
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        //查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "CreateTime"));
        //报送任务列表
        Page<UsualTask> taskPage = usualTaskRepository.findPage(query, PageRequest.of(page - 1, size));
        //今日报送情况
        Integer state = null;
        //封装返回数据
        List<UsualTaskVO> taskVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(taskPage.getContent())) {
            for (UsualTask task : taskPage.getContent()) {
                UsualTaskVO taskVO = new UsualTaskVO();
                taskVO.setUsualCode(task.getUsualCode());
                taskVO.setTitle(task.getTitle());
                taskVO.setStartTime(task.getStartTime());
                taskVO.setEndTime(task.getEndTime());
                //开始时间
                LocalDateTime start = DateSwitcher.getMinTime(LocalDateTime.now());
                //结束时间
                LocalDateTime end = DateSwitcher.getMaxTime(LocalDateTime.now());
                //查询条件
                Query search = new Query();
                search.addCriteria(Criteria.where("UsualCode").is(task.getUsualCode()));
                search.addCriteria(Criteria.where("SiteCode").is(user.getSiteCode()));
                search.addCriteria(Criteria.where("Time").gt(start).andOperator(Criteria.where("Time").lt(end)));
                //今日报送情况
                Usual usual = usualRepository.findOne(search);
                if (state == null) {
                    if (usual == null) {
                        //今日未报送
                        state = 0;
                    } else {
                        //今日已报送
                        state = 1;
                    }
                }
                taskVOS.add(taskVO);
            }
        }
        //分页信息
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(taskPage.getContent().size());
        pageInfo.setTotal(taskPage.getTotalElements());
        //封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("state", state);
        map.put("usualTaskList", taskVOS);
        map.put("pageInfo", pageInfo);
        return new Return(map);
    }

    @Override
    public List<UsualTask> selectRunningUsualTask() {
        LocalDate date = LocalDate.now().minusDays(1);
        List<UsualTask> taskList
                = usualTaskRepository.findAll(new Query().addCriteria(Criteria.where("StartTime").lte(date).and("EndTime").gte(date)));
        if (CollectionUtils.isEmpty(taskList)) {
            return new ArrayList<>();
        }
        return taskList;
    }

    @Override
    public UsualTaskVO usualTaskDetails(String usualCode) {
        UsualTaskVO vo = new UsualTaskVO();
        UsualTask usualTask = usualTaskRepository.findByPrimaryKey(usualCode);
        if (usualTask != null) {
            BeanUtils.copyProperties(usualTask, vo);
        }
        return vo;
    }

    @Override
    public void delete(String usualCode) {
        usualTaskRepository.deletePrimaryKey(usualCode);
    }

    @Override
    public Return update(String usualCode, String title, String startTime, String endTime) {
        UsualTask usualTask = usualTaskRepository.findByPrimaryKey(usualCode);
        if (usualTask == null) {
            return new Return(Return.FAIL, "报送任务数据不存在");
        }
        try {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate startDate = LocalDate.parse(startTime, dtf);
            LocalDate endDate = LocalDate.parse(endTime, dtf);
            if (startDate.compareTo(endDate) > 0) {
                return new Return(Return.FAIL, "开始时间不能大于结束时间");
            }
            usualTask.setStartTime(startDate);
            usualTask.setEndTime(endDate);
        } catch (Exception e) {
            return new Return(Return.FAIL, "日期格式不正确");
        }
        usualTask.setTitle(title);
        usualTask.setUpdateTime(LocalDateTime.now());
        usualTaskRepository.updateByPrimaryKey(usualTask);
        return new Return(Return.SUCCESS, "修改成功");
    }
}
